﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ProgNetComponentsDx.Browsers;
using System.IO;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Options;

namespace BuildHelper.Work.Tortoise
{
    public partial class TortoiseForm : XtraForm
    {
        public TortoiseForm()
        {
            InitializeComponent();
            if (!this.IsDesignMode())
            {
                xtraTabControl1.SetTabMinSize(120);
                ceTylkoLokalne_CheckedChanged(ceTylkoLokalne, EventArgs.Empty);
                fileBgAppender1.FileName = GlobalTools.FilesTools.GetTemplLogFile("Tortoise");
                Setup.Brancze.BranczeTools.ActiveBranchChanged += new EventHandler(BranczeTools_ActiveBranchChanged);
                OptionCache.OptionChanged += new OptionChangedEventHandler(OptionCache_OptionChanged);
                OptionCache_OptionChanged(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile);
                BranczeTools_ActiveBranchChanged(null, null);
            }
        }

        void BranczeTools_ActiveBranchChanged(object sender, EventArgs e)
        {
            lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
            lueBranczLogi.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
        }
        ~TortoiseForm()
        {
            OptionCache.OptionChanged -= OptionCache_OptionChanged;
            Setup.Brancze.BranczeTools.ActiveBranchChanged -= new EventHandler(BranczeTools_ActiveBranchChanged);
        }
        void OptionCache_OptionChanged(object optionId)
        {
            if(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.AutoAdd.IsTheSameKey(optionId) ||
                Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile.IsTheSameKey(optionId))
            {
                logFile = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile);

                btnLogAddToFile.Enabled = !OptionCache.GetOptionBoolValue(optionId) && logFile.IsNotNullOrEmpty();
                btnShowLog.Enabled = logFile.IsNotNullOrEmpty();
            }
        }

        private Process process;
        private const string MSG_CHECK_OUT_DONE = "CheckOut zakończony";
        private const string MSG_UPDATE_DONE = "Update zakończony";
        private const string MSG_CLEANUP_DONE = "Cleanup zakończony";
        private const string MSG_NAPRAWIANIE_DONE = "Naprawianie zakończone";
        private const string MSG_CANCEL = "Operacja anulowana.";

        private void KoniecOperacji(string message)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(KoniecOperacji), message);
                return;
            }
            if (message == MSG_CANCEL)
                FormMain.ShowWarningAlert(message);
            else
                FormMain.ShowInfoAlert(message);

            memoBgAppender1.Finish();
            fileBgAppender1.Finish();

            try
            {
                process.KillProcessTree();
                process.Dispose();
            }
            catch { }
            process = null;
            marqueeProgressBarControl1.Properties.Stopped = true;
            marqueeProgressBarControl1.Text = "";
            FormMain.CloseAlertById("CHECK_OUT");
        }

        string CheckOutBrancz;
        bool isSvnCheckOut = false;
        int maxApps = 0;
        int curApp = 0;
        int maxDirs = 0;
        int curDir = 0;

        private void PoczatekOpracji()
        {
            isSvnCheckOut = false;
            maxApps = 0;
            curApp = 0;
            maxDirs = 0;
            curDir = 0;

            marqueeProgressBarControl1.Properties.Stopped = false;
            meLogCheckOut.Text = "";
            "".WriteToFile(fileBgAppender1.FileName);
            fileBgAppender1.Start();
            memoBgAppender1.Start();
            if (splitContainerControl1.Collapsed)
            {
                splitContainerControl1.Collapsed = false;
                splitContainerControl1.SplitterPosition = this.Height - 490;
            }
        }
        private void CheckOutUpdate(bool checkOut)
        {
            if (process == null)
            {
                string brancz = lueBrancz.EditValue.AsString();
                if (brancz.IsNull())
                {
                    this.ShowDxInfoDialog("Wybierz brancza.");
                    return;
                }
                if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
                {
                    this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n" +
                        GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                    return;
                }
                Setup.Brancze.BranczeDataSet ds = new Setup.Brancze.BranczeDataSet();
                sqlCeDataManager1.FillTable(ds.STP_BRANCZE, "SELECT * FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql());
                sqlCeDataManager1.FillTable(ds.STP_BRANCZE_APPS, "SELECT * FROM STP_BRANCZE_APPS WHERE STP_BR_APP_BRANCZ=" + brancz.EscapeSql());
                
                if (ds.STP_BRANCZE.Rows.Count == 1)
                {
                    DataRow r = ds.STP_BRANCZE[0];
                    string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                    string gene = katalog + "\\nd_src\\gene";
                    string apps = katalog + "\\nd_src\\gene\\apps";
                    string svn = r["STP_BR_SVN"].AsString();
                    DataRow svnRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, svn);
                    if (svnRow.IsNull())
                    {
                        this.ShowDxErrorDialog("Nie można odnalećś url dla brancza.");
                        return;
                    }
                    string svnUrl = svnRow["URL"].AsString().TrimEnd('/');
                    List<string> systems = new List<string>();
                    foreach (string sys in GlobalTools.Systems)
                    {
                        if (ds.STP_BRANCZE_APPS.SelectFirstRow("STP_BR_APP_APP = " + sys.EscapeSql()) != null)
                        {
                            systems.Add(sys.ToLower());
                            if (sys == "GCM")
                                systems.Add("csm");
                        }
                    }

                    if (checkOut)
                    {
                        if (Directory.Exists(gene))
                        {
                            this.ShowDxErrorDialog("Katalog gene istnieje. Nie można wykonać CheckOut.");
                            return;
                        }
                        Directory.CreateDirectory(gene);
                    }
                    else
                    {
                        if (!Directory.Exists(apps))
                        {
                            this.ShowDxErrorDialog("Katalog apps nie istnieje. Nie można wykonać Update.");
                            return;
                        }
                    }
                    process = GlobalTools.CreateCMDProcess(CheckOutUpdate_Data);

                    PoczatekOpracji();
                    string[] dirs = GlobalTools.TortoiseTools.GetDirectories(svnUrl);

                    if (checkOut)
                    {
                        this.isSvnCheckOut = true;
                        this.maxDirs = dirs.Length-1;//remove apps
                        this.maxApps = systems.Count;
                        CheckOutBrancz = brancz;
                        BuildHelper.FormMain.AlertInfo ai = new FormMain.AlertInfo(true, "CHECK_OUT");
                        ai.Centerid = false;
                        FormMain.ShowAlert("SVN CheckOut [" + CheckOutBrancz + "]", Properties.Resources.tortoise24, ai);
                    }
                    process.CdDir(gene);
                    GlobalTools.TortoiseTools.AddSvnToPath(process);
                    if (checkOut)
                        process.Execute("svn co --depth files " + svnUrl + " .");
                    else
                    {
                        if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise.AutoCleanup))
                            process.Execute("svn cleanup");
                        process.Execute("svn up --non-interactive");
                    }
                    
                    foreach (string dir in dirs)
                    {
                        if (!dir.XMatch("^apps$"))
                        {
                            process.Execute("svn up --set-depth infinity --non-interactive " + dir);
                        }
                    }
                    if (checkOut)
                        process.Execute("svn up --set-depth empty --non-interactive apps");
                    foreach (string sys in systems)
                    {
                        process.Execute("svn up --set-depth infinity --non-interactive apps/" + sys);
                    }
                    if(checkOut)
                        process.Echo(MSG_CHECK_OUT_DONE);
                    else
                        process.Echo(MSG_UPDATE_DONE);
                }
                else
                {
                    this.ShowDxErrorDialog("Nie można wybrać brancza.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }
        #region CheckOut
        private void btnCheckOut_Click(object sender, EventArgs e)
        {
            CheckOutUpdate(true);
        }
        private void CheckOutUpdate_Data(object sender, DataReceivedEventArgs e)
        {
            string str = e.Data.AsString();
            if (str == MSG_CHECK_OUT_DONE ||
                str == MSG_UPDATE_DONE ||
                str == MSG_CLEANUP_DONE ||
                str == MSG_NAPRAWIANIE_DONE)
            {
                KoniecOperacji(str);
            }
            else
            {
                if (isSvnCheckOut)
                {
                    if (str.XMatch("svn up --set-depth infinity --non-interactive apps/"))
                    {
                        curApp++;
                        SetProgress();
                    }
                    else  if (str.XMatch("svn up --set-depth infinity --non-interactive"))
                    {
                        curDir++;
                        SetProgress();
                    }
                }
                if (!str.XMatch("echo ") && !str.XMatch("[\\w]:$")&& !str.XMatch("cd "))
                {
                    if (str.XMatch("^Pomijam "))
                    {
                        if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise.PokazujInfoOPominieciach))
                            memoBgAppender1.Append(str);
                    }
                    else
                        memoBgAppender1.Append(str);

                    fileBgAppender1.Append(str);
                }
            }
        }

        private void SetProgress()
        {
            if (marqueeProgressBarControl1.InvokeRequired)
            {
                this.Invoke(new Action(SetProgress));
                return;
            }
            string text = "Katalog: " + curDir + "/" + maxDirs + " ; App:" + curApp + "/" + maxApps;
            marqueeProgressBarControl1.Text = text;
            FormMain.UpdateAlertText("CHECK_OUT", "SVN CheckOut [" + CheckOutBrancz + "]" + Constants.NewLineLinux +
                text.Replace(";", Constants.NewLineLinux));
        }
        #endregion

        #region Update
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            CheckOutUpdate(false);
        }
       
        #endregion

        private void btnCleanUp_Click(object sender, EventArgs e)
        {
            if (process == null)
            {
                string brancz = lueBrancz.EditValue.AsString();
                if (brancz.IsNull())
                {
                    this.ShowDxInfoDialog("Wybierz brancza.");
                    return;
                }
                if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
                {
                    this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n" +
                        GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                    return;
                }
                Setup.Brancze.BranczeDataSet ds = new Setup.Brancze.BranczeDataSet();
                sqlCeDataManager1.FillTable(ds.STP_BRANCZE, "SELECT * FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql());
                sqlCeDataManager1.FillTable(ds.STP_BRANCZE_APPS, "SELECT * FROM STP_BRANCZE_APPS WHERE STP_BR_APP_BRANCZ=" + brancz.EscapeSql());
                
                if (ds.STP_BRANCZE.Rows.Count == 1)
                {
                    DataRow r = ds.STP_BRANCZE[0];
                    string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                    string gene = katalog + "\\nd_src\\gene";
                    string apps = katalog + "\\nd_src\\gene\\apps";
                    string svn = r["STP_BR_SVN"].AsString();
                    DataRow svnRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, svn);
                    if (svnRow.IsNull())
                    {
                        this.ShowDxErrorDialog("Nie można odnalećś url dla brancza.");
                        return;
                    }
                    string svnUrl = svnRow["URL"].AsString().TrimEnd('/');
                    List<string> systems = new List<string>();
                    foreach (string sys in GlobalTools.Systems)
                    {
                        if (ds.STP_BRANCZE_APPS.SelectFirstRow("STP_BR_APP_APP = " + sys.EscapeSql()) != null)
                        {
                            systems.Add(sys.ToLower());
                        }
                    }

                    if (!Directory.Exists(gene))
                    {
                        this.ShowDxErrorDialog("Katalog gene nie istnieje. Nie można wykonać Update.");
                        return;
                    }
                    process = GlobalTools.CreateCMDProcess(CheckOutUpdate_Data);

                    PoczatekOpracji();

                    process.CdDir(gene);
                    GlobalTools.TortoiseTools.AddSvnToPath(process);
                    process.Execute("svn cleanup");
                    process.Echo(MSG_CLEANUP_DONE);
                }
                else
                {
                    this.ShowDxErrorDialog("Nie można wybrać brancza.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        private void btnAnuluj_Click(object sender, EventArgs e)
        {
            if (process != null)
            {
                KoniecOperacji(MSG_CANCEL);
            }
        }

        private void btnUpdateDirByDir_Click(object sender, EventArgs e)
        {
            if (process == null)
            {
                string brancz = lueBrancz.EditValue.AsString();
                if (brancz.IsNull())
                {
                    this.ShowDxInfoDialog("Wybierz brancza.");
                    return;
                }
                if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
                {
                    this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n" +
                        GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                    return;
                }
                Setup.Brancze.BranczeDataSet ds = new Setup.Brancze.BranczeDataSet();
                sqlCeDataManager1.FillTable(ds.STP_BRANCZE, "SELECT * FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql());
                sqlCeDataManager1.FillTable(ds.STP_BRANCZE_APPS, "SELECT * FROM STP_BRANCZE_APPS WHERE STP_BR_APP_BRANCZ=" + brancz.EscapeSql());
                
                if (ds.STP_BRANCZE.Rows.Count == 1)
                {
                    DataRow r = ds.STP_BRANCZE[0];
                    string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                    string gene = katalog + "\\nd_src\\gene";
                    string apps = katalog + "\\nd_src\\gene\\apps";
                    string svn = r["STP_BR_SVN"].AsString();
                    DataRow svnRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, svn);
                    if (svnRow.IsNull())
                    {
                        this.ShowDxErrorDialog("Nie można odnalećś url dla brancza.");
                        return;
                    }
                    string svnUrl = svnRow["URL"].AsString().TrimEnd('/');
                    List<string> systems = new List<string>();
                    foreach (string sys in GlobalTools.Systems)
                    {
                        if (ds.STP_BRANCZE_APPS.SelectFirstRow("STP_BR_APP_APP = " + sys.EscapeSql()) != null)
                        {
                            systems.Add(sys.ToLower());
                            if (sys == "GCM")
                                systems.Add("csm");
                        }
                    }

                    if (!Directory.Exists(apps))
                    {
                        this.ShowDxErrorDialog("Katalog apps nie istnieje. Nie można naprawić.");
                        return;
                    }
                    process = GlobalTools.CreateCMDProcess(CheckOutUpdate_Data);

                    PoczatekOpracji();

                    process.CdDir(gene);
                    GlobalTools.TortoiseTools.AddSvnToPath(process);
                    process.Echo("Naprawianie %cd%");
                    process.Execute("svn up --depth files");
                    string bat = GlobalTools.FilesTools.GetTemplLogFile("batfile", "bat");
                    if(OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise.NaprawaTylkoBrakujaceKatalogi))
                        Properties.Resources.SvnUpdateScript1.WriteToFile(bat, Encoding.Default);
                    else
                    Properties.Resources.SvnUpdateScript.WriteToFile(bat, Encoding.Default);

                    if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise.AutoCleanup))
                        process.Execute("svn cleanup");
                    string[] dirs = GlobalTools.TortoiseTools.GetDirectories(svnUrl);
                    foreach (string dir in dirs)
                    {
                        if (!dir.XMatch("^apps$"))
                        {
                            process.Execute("call " + bat.AddDoubleQuotes() + " " + dir);
                        }
                    }
                    process.CdDir(gene + "\\apps");

                    foreach (string sys in systems)
                    {
                        process.Execute("call " + bat.AddDoubleQuotes() + " " + sys);
                    }
                    process.Echo(MSG_NAPRAWIANIE_DONE);
                }
                else
                {
                    this.ShowDxErrorDialog("Nie można wybrać brancza.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        private void btnPokazPelnyLog_Click(object sender, EventArgs e)
        {
            GlobalTools.FilesTools.RunFile(fileBgAppender1.FileName, "");
        }

        #region Logi
        string logFile = "";
        Process procLogi;

        private void teRewizjaLogi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnShowLog.PerformClick();
        }

        private void btnShowLog_Click(object sender, EventArgs e)
        {
            if (procLogi != null)
            {
                this.ShowDxErrorDialog("Operacja w toku");
                return;
            }
            string brancz = lueBranczLogi.EditValue.AsString();
            string rev = teRewizjaLogi.EditValue.AsString();
            if (brancz.IsNull())
            {
                this.ShowDxErrorDialog("Wybierz brancza");
                return;
            }
            if (ceTylkoLokalne.Checked)
            {
                object dr = lueBranczLogi.GetSelectedDataRow();
                if (dr != null && dr is DataRowView)
                {
                    brancz = (dr as DataRowView)["STP_BR_SVN"].AsString();
                }
            }
            if (rev.IsNull())
            {
                this.ShowDxErrorDialog("Podaj rewizję");
                return;
            }
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, brancz);
            string path = "";
            if (r == null)
            {
                this.ShowDxErrorDialog("Nie można odnaleźć brancza " + brancz);
                return;
            }
            if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
            {
                this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n"+
                    GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                return;
            }

            path = r["URL"].AsString();
            procLogi = GlobalTools.CreateCMDProcess(procLogi_Data);
            
            string cmd = "svn log " + path + " -r " + rev + " --incremental --verbose ";
            procLogiAdd = false;
            memoLogi.Text = "";
            memoBgAppender2.Start();
            progressLogi.Properties.Stopped = false;
            procLogi.EchoOff();
            GlobalTools.TortoiseTools.AddSvnToPath(process);
            procLogi.Execute(cmd);
            procLogi.Echo("exit");
        }

        private void procLogiFinish(bool isLogi = true)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<bool>(procLogiFinish), isLogi);
                return;
            }
            procLogiAdd = false;
            memoBgAppender2.Finish();
            try
            {
                procLogi.CallExit();
                procLogi.KillProcessTree();
                procLogi.Dispose();
            }
            catch { }

            procLogi = null;
            progressLogi.Properties.Stopped = true;
            if (isLogi)
            {
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.AutoAdd))
                {
                    AddLogi();
                }
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.KopiujDoSchowka))
                {
                    Clipboard.SetText(memoLogi.Text);
                }
            }
        }

        private void AddLogi()
        {
            if (logFile.IsNullOrEmpty())
            {
                this.ShowDxErrorDialog("Brak pliku. Sprawdź opcje.\n" 
                    + GlobalTools.GetOptionPath(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile));
                return;
            }
            string log = memoLogi.Text;
            if (log.IsNotNullOrEmpty())
            {
                log = log + Constants.NewLineLinux;
                log.AppendToFile(logFile);
                FormMain.ShowInfoAlert("Log zapisany");
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.AutoClearAfterAdd))
                {
                    memoLogi.Text = "";
                }
            }
        }

        private bool procLogiAdd = false;
        private void procLogi_Data(object sender, DataReceivedEventArgs e)
        {
            string msg = e.Data.AsString();
            if (msg.XMatch("^echo exit"))
                procLogiFinish();
            else if (procLogiAdd)
            {
                memoBgAppender2.Append(msg);
            }
            else if (msg.XMatch("svn log"))
            {
                procLogiAdd = true;
            }
        }

        private void btnLogClear_Click(object sender, EventArgs e)
        {
            memoLogi.Text = "";
        }

        private void btnLogAddToFile_Click(object sender, EventArgs e)
        {
            AddLogi();
        }

        private void btnOtworzPlik_Click(object sender, EventArgs e)
        {
            if (logFile.IsNullOrEmpty())
            {
                this.ShowDxErrorDialog("Brak pliku. Sprawdź opcje.");
                return;
            }
            GlobalTools.FilesTools.RunFile(logFile);
        }
        #endregion

        private void ceTylkoLokalne_CheckedChanged(object sender, EventArgs e)
        {
            string old = lueBranczLogi.EditValue.AsString();
            browserProvider1.GetSettings(lueBranczLogi).BeginSettings();

            if (ceTylkoLokalne.Checked)
            {
                browserProvider1.GetSettings(lueBranczLogi).BrowserId = Init.InitFormBrowserNames.Setup.BranczeAktywne;
                browserProvider1.GetSettings(lueBranczLogi).AdditionalBrowserId = Init.InitFormBrowserNames.Setup.Brancze;
                browserProvider1.GetSettings(lueBranczLogi).AdditionalBrowserDisplayType = BrowserSettingsDisplayType.DialogWindow;
                browserProvider1.GetSettings(lueBranczLogi).AddBrowserDialogButton = false;
            }
            else
            {
                browserProvider1.GetSettings(lueBranczLogi).BrowserId = Init.InitFormBrowserNames.Statyczne.BranczeSVN;
                browserProvider1.GetSettings(lueBranczLogi).AdditionalBrowserId = null;
                browserProvider1.GetSettings(lueBranczLogi).AddBrowserDialogButton = true;
            }
            browserProvider1.GetSettings(lueBranczLogi).EndSettings();

            if (BrowserCache.IsValid(browserProvider1.GetSettings(lueBranczLogi).BrowserId, true, old) ||
                BrowserCache.IsValid(browserProvider1.GetSettings(lueBranczLogi).AdditionalBrowserId, true, old))
            {
                lueBranczLogi.EditValue = old;
            }
        }
        #region TortoiseProc
        private void RunTortoise(string command, bool addUrl = false, bool useApps = false)
        {
            GlobalTools.TortoiseTools.RunTortoise(lueBrancz.EditValue.AsString(), command, addUrl, useApps);
        }

        private void btnCheckOutTortoise_Click(object sender, EventArgs e)
        {
            RunTortoise("checkout", true);
        }

        private void btnUpdateTortoise_Click(object sender, EventArgs e)
        {
            RunTortoise("update");
        }

        private void btnLogTortoise_Click(object sender, EventArgs e)
        {
            RunTortoise("log", useApps: OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise.DirForLog) == "A");
        }

        private void btnZmianyTortoise_Click(object sender, EventArgs e)
        {
            RunTortoise("repostatus", useApps: OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise.DirForZmiany) == "A");
        }

        private void btnCleanupTortoise_Click(object sender, EventArgs e)
        {
            RunTortoise("cleanup");
        }
        private void btnCommitTortoise_Click(object sender, EventArgs e)
        {
            if (lueBrancz.EditValue.IsNotNull())
                GlobalTools.TortoiseTools.Commit(lueBrancz.EditValue.AsString());
            else
                this.ShowDxInfoDialog("Wybierz brancza");
        }
        #endregion

        private void btnPokazWTortoise_Click(object sender, EventArgs e)
        {
            string rev = teRewizjaLogi.EditValue.AsString();
            if (rev.IsNotNullOrEmpty())
            {
                RunTortoise("log /startrev:" + rev + " /endrev:" + rev, useApps: true);
            }
        }

        private void btnPokazLogWTortoise_Click(object sender, EventArgs e)
        {
            string command = "log";
            string rev = teRewizjaLogi.EditValue.AsString();
            if(rev.IsNotNullOrEmpty())
                command += " /startrev:" + rev + " /endrev:" + rev;

            if (ceTylkoLokalne.Checked)
            {
                GlobalTools.TortoiseTools.RunTortoise(lueBranczLogi.Text, command);
            }
            else
            {
                GlobalTools.TortoiseTools.RunTortoiseGlobal(lueBranczLogi.Text, command, "", true);
            }
        }

        private void btnPatch_Click(object sender, EventArgs e)
        {
            if (procLogi != null)
            {
                this.ShowDxErrorDialog("Operacja w toku");
                return;
            }
            string brancz = lueBranczLogi.EditValue.AsString();
            string rev = teRewizjaLogi.EditValue.AsString();
            if (brancz.IsNull())
            {
                this.ShowDxErrorDialog("Wybierz brancza");
                return;
            }
            if (ceTylkoLokalne.Checked)
            {
                object dr = lueBranczLogi.GetSelectedDataRow();
                if (dr != null && dr is DataRowView)
                {
                    brancz = (dr as DataRowView)["STP_BR_SVN"].AsString();
                }
            }
            if (rev.IsNull())
            {
                this.ShowDxErrorDialog("Podaj rewizję");
                return;
            }
            DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, brancz);
            string path = "";
            if (r == null)
            {
                this.ShowDxErrorDialog("Nie można odnaleźć brancza " + brancz);
                return;
            }
            if (!GlobalTools.TortoiseTools.CanUseTortoiseSvn())
            {
                this.ShowDxErrorDialog("Brak svn. Sprawdź opcje.\n" +
                    GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn));
                return;
            }

            path = r["URL"].AsString();
           
            int prevRev = rev.AsInt() - 1;
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                procLogi = GlobalTools.CreateCMDProcess(procLogi_DataPatch);
                string cmd = "svn diff " + " -r " + prevRev + ":" + rev + " " + path + " > " + saveFileDialog1.FileName.AddDoubleQuotes();
                procLogiAdd = false;
                memoLogi.Text = "";
                memoBgAppender2.Start();
                progressLogi.Properties.Stopped = false;
                procLogi.EchoOff();
                GlobalTools.TortoiseTools.AddSvnToPath(process);
                procLogi.Execute(cmd);
                procLogi.Echo("exit");
            }
        }

        private void procLogi_DataPatch(object sender, DataReceivedEventArgs e)
        {
            string msg = e.Data.AsString();
            if (msg.XMatch("^echo exit"))
            {
                FormMain.ShowInfoAlert("Patch zapisany");
                procLogiFinish(false);
            }
        }

    }
}
